import GlobalAutoConfigurable from "@framework/config/GlobalAutoConfigurable";
import Log4j, {Logger} from 'koa-log4';

Log4j.configure({
    appenders: {
        access: GlobalAutoConfigurable.logger,
        out: {
            type: 'stdout',
            layout: GlobalAutoConfigurable.logger.layout
        }
    },
    categories: {
        default: { appenders: ['out'], level: GlobalAutoConfigurable.logger.root },
        access: { appenders: ['access'],  level: GlobalAutoConfigurable.logger.root },
    }
})

/**
 * 日志封装
 */
class KoaBootLogger {

    /**
     * log4j日志实例
     * @private
     */
    private logger: Logger;

    /**
     * log4j日志默认实例
     * @private
     */
    private defaultLogger: Logger;

    /**
     * 自身实力
     * @private
     */
    private static koaLogger: KoaBootLogger;

    constructor() {
        this.logger = Log4j.getLogger("access");
        this.defaultLogger = Log4j.getLogger();
    }

    /**
     * 单例模式，懒汉式
     */
    public static getInstance(): KoaBootLogger {
        if (KoaBootLogger.koaLogger) {
            return KoaBootLogger.koaLogger;
        }
        KoaBootLogger.koaLogger = new KoaBootLogger();
        return KoaBootLogger.koaLogger;
    }

    public info(message: any, ...args: any[]) {
        if (args && args.length > 0) {
            this.logger.info(message, args);
            this.defaultLogger.info(message, args);
        } else {
            this.logger.info(message);
            this.defaultLogger.info(message);
        }
    }

    public debug(message: any, ...args: any[]) {
        if (args && args.length > 0) {
            this.logger.debug(message, args);
            this.defaultLogger.debug(message, args);
        } else {
            this.logger.debug(message);
            this.defaultLogger.debug(message);
        }
    }

    public warn(message: any, ...args: any[]) {
        if (args && args.length > 0) {
            this.logger.warn(message, args);
            this.defaultLogger.warn(message, args);
        } else {
            this.logger.warn(message);
            this.defaultLogger.warn(message);
        }
    }

    public error(message: any, ...args: any[]) {
        if (args && args.length > 0) {
            this.logger.error(message, args);
            this.defaultLogger.error(message, args);
        } else {
            this.logger.error(message);
            this.defaultLogger.error(message);
        }
    }
}

export default KoaBootLogger;